// pages/coinCertificateImg/coinCertificateImg.js
import api from "../../config/api";
import request from "../../utils/request";
import { shareOptions } from "../../utils/access";
import { jump,stringify, goBack } from '../../utils/utils'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    selectTab:1,
    tabTypeFlag:1,
    addressee:null, // 收件人信息
    // 券码id
    id:null,
    imgUrl:'',
    couponName:'',
    // 当前页
    loading:false,
    timeout: 3000,// 请求接口超时时间
  },
  // 前往兑换列表 未兑换页面
  go(){
    wx.navigateBack({
      delta: 1,
    })
  },
  clickLeftTab(){
   this.setData({
     selectTab:1
   })
  },
  clickRightTab(){
   this.setData({
     selectTab:2,
     couponName:this.data.couponName.replace('兑换券','')
   })
  },
  async getUserReceiveList(){
    const res = await request.get(api.userReceiveList)
    console.log('ressss',res);
    if(res.httpStatus===200&&res.data){
      this.setData({
        addressee:res.data
      })
    }
  },
  // 点击提交
  handleSubmit(){
    const {addressee} = this.data
    if(addressee===null){
      return
    }
    if(addressee.recipientName.replace(/\s*/g,"").length<2){
      wx.showToast({
        title: '姓名最短2个字',
        icon:'none'
      })
      return
    }
    if(addressee.recipientName.replace(/\s*/g,"").length>15){
      wx.showToast({
        title: '姓名最长15个字',
        icon:'none'
      })
      return
    }
    let reg= /[^A-Za-z\u4e00-\u9fa5]+/;
    if(reg.test(addressee.recipientName)){
      wx.showToast({
        title: '姓名只能用中文或英文',
        icon: 'none'
      })
      return 
    }
    this.addressModal.show()
  },
  // 点击弹窗--取消
  cancle(){
    this.addressModal.hide()
  },
  // 点击弹窗--提交
  async submit(){
    if(this.loading) return
    this.loading = true
    const {addressee,couponName,goodsid} = this.data
    
    const res = await request.post(api.coinCertificateSubmitOrder,{
      goodsName:couponName,
      sourceId:Number(goodsid),
      userReceiveInfoId:addressee.id
    })
    if(res.httpStatus===200){
      this.addressModal.hide()
      wx.showToast({
        title: '提交成功',
        icon:'none'
      })

      let pages = getCurrentPages();
      let prePage = pages[pages.length - 2]
        prePage.setData({
          isShow:2
      })
      setTimeout(()=>{
        this.loading = false
        // prePage.showServiceModal()
        wx.navigateBack({
          delta: 1,
        })
      },1500)
    }else{
      wx.showToast({
        title: '提交失败',
        icon:'none'
      })
      this.loading = false
    }
  },
  // 1.0 根据券码id获取券码图片
  async getImg(){
    let that = this
    const { id ,timeout } = that.data
    console.log(id)
    // 新接口
    const res = await request.get(api.getQRcode,{
      code:id
    },{ responseType: 'arraybuffer' ,timeout: timeout})
    // 请求报错
    if(res.errMsg && res.errMsg.indexOf("请求超时") !== -1){
      wx.showModal({
        content: '当前网络环境不好',
        cancelText: '关闭',
        confirmText: "重新加载",
        success(res) {
          if (res.confirm) {
            that.setData({
              timeout: 5000
            }, () => {
              that.getImg()
            })
          }
        }
      })
      return
    }
    console.log(res)
    const fileManager = wx.getFileSystemManager()
    const filePath = `${wx.env.USER_DATA_PATH}/${Date.now()}.jpg`
    fileManager.writeFileSync(filePath, res, 'binary')
    console.log(filePath)
    this.setData({
      imgUrl:filePath,
      timeout: 3000
    })
  },
  // 拨打电话
  async callPhone(){
    const { loading } = this.data
    if (loading) return
    this.setData({
      loading:true
    })
    wx.makePhoneCall({
      phoneNumber: '0371-53376036',
      fail: (error) => {

        // console.log(error)
        // wx.showToast({
        //   title: '拨打失败，请重试',
        //   icon: 'none'
        // })
      },
      complete: () => {
        this.setData({
          loading: false
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('tabTypeFlag',options);
    this.setData({
      id:options.id,
      goodsid:options.goodsId,
      couponName:options.tabTypeFlag==='2'?options.couponName.replace('兑换券',''):options.couponName,
      tabTypeFlag:options.tabTypeFlag,
      selectTab:options.tabTypeFlag==='2'?2:1
    })
    this.getImg()
    
  },
  // 创建收件人信息
  toCreateInfo:function(){
    jump('addresseeInfo')
  },
  // 修改收件人信息
  toEditInfo:function(){
    const {addressee} = this.data
    let info = stringify(addressee)
    jump('addresseeInfo',{info})
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.addressModal = this.selectComponent('#addressModal')
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getUserReceiveList()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage(e) {
    return shareOptions('default', e)
  },
})